package com.huike.clues.service.impl;

import com.huike.clues.service.ISysFileService;
import com.huike.common.config.MinioConfig;
import com.huike.common.core.domain.AjaxResult;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@Slf4j
public class SysFileServiceImpl implements ISysFileService {

    @Autowired
    private MinioConfig minioConfig;

    /**
     * 文件上传至Minio
     */
    @Override
    public AjaxResult upload(MultipartFile file) throws Exception {

        //创建Minio的连接对象
        MinioClient minioClient = MinioClient.builder().endpoint(minioConfig.getEndpoint() + ":" + minioConfig.getPort())
                .credentials(minioConfig.getAccessKey(), minioConfig.getSecretKey()).build();
        String bucketName = minioConfig.getBucketName();
        //判断文件存储的桶是否存在
        boolean found = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
        if (!found) {
            //如果桶不存在则创建通
            minioClient.makeBucket(MakeBucketArgs.builder().bucket(bucketName).build());
        }
        //操作文件
        String fileName = file.getOriginalFilename();
        String objectName = new SimpleDateFormat("yyyy/MM/dd/").format(new Date()) + UUID.randomUUID().toString().replaceAll("-", "") + fileName.substring(fileName.lastIndexOf("."));
        //文件上传
        //由于使用的是SpringBoot与之进行集成 上传的时候拿到的是MultipartFile 需要通过输入输出流的方式进行添加
        PutObjectArgs objectArgs = PutObjectArgs.builder().object(objectName)
                .bucket(bucketName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), -1).build();
        minioClient.putObject(objectArgs);
        //封装访问的url给前端
        AjaxResult ajax = AjaxResult.success();
        ajax.put("fileName", "/" + bucketName + "/" + objectName);
        ajax.put("url", minioConfig.getEndpoint() + ":" + minioConfig.getPort() + "/" + bucketName + "/" + objectName);
        return ajax;


    }

}
